/**
 * Created by 55456 on 2016/4/8.
 */
var BaseController = require("./BaseController");
var util = require("util");
var crypto = require('crypto');
var cache = require("../instances/cache");

var LoginController = function LoginController(attr){
    BaseController.apply(this,arguments);
};

util.inherits(LoginController,BaseController);

//return promise
LoginController.prototype.login = function (ctx,db) {
    if(arguments.length < 4){
        throw("login arguments length can not less then 4");
    }
    //todo:auto checkAttr
    this.CheckAttr(arguments[0]);
    //
    var User = arguments[1];
    var checkObj = this._parseWhereArgs(arguments);
    return User.findOne({
        where:checkObj
    }).then(function(result){
        if(result){
            //todo:extend to accept more args
            var token = LoginController.prototype.md5(result.pwd +"&"+ result.mobile);
            cache._client.jsetex(token,60 * 60,result);
            return {token:result.token,LoginToken:token,userID:result.id};
        }else{
            return null;
        }
    });
};

LoginController.prototype.debugLogin = function (ctx,db) {
    this.CheckAttr(arguments[0]);
    var User = arguments[1];
    return User.findOne({
    }).then(function(result){
        if(result){
            var token = "OurEDA";
            return {token:token,user:result};
        }else{
            throw("Debug Login need at least one data in database");
        }
    });
};

var Login = new LoginController("public");
module.exports = Login;